package br.com.dispositivosmoveis.acompanhamentodeconta.abstracts;

import java.util.List;

import android.app.Activity;
import android.database.sqlite.SQLiteConstraintException;
import br.com.dispositivosmoveis.acompanhamentodeconta.database.DataBaseHelper;
import br.com.dispositivosmoveis.acompanhamentodeconta.util.GenericsReader;

public abstract class AbstractActivity<E, S extends AbstractService<E>> extends
		Activity {
	private S service;
	private E instance;
	private Class<E> instanceClass;
	private Class<S> serviceClass;

	public abstract void startEvents();

	public void persit() {
		try {
			this.getService().insert(this.getInstance());
		} catch (SQLiteConstraintException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void update() {
		try {
			this.getService().update(this.getInstance());
		} catch (SQLiteConstraintException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public E findById(int id) {
		return this.getService().obtain(id);
	}

	public List<E> getAll() {
		return this.getService().getAll();
	}

	public boolean formValidate(E entity) {
		return true;
	}

	public S getService() {
		if (this.service == null) {
			this.service = this.newService();
		}
		return service;
	}

	public E getInstance() {
		if (this.instance == null) {
			this.instance = this.newInstance();
		}
		return instance;
	}

	private S newService() {
		try {
			return this.getServiceClass().newInstance();
		} catch (final Exception e) {
			return null;
		}
	}

	private E newInstance() {
		try {
			return this.getEntityClass().newInstance();
		} catch (final Exception e) {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	private Class<S> getServiceClass() {
		if (this.serviceClass == null) {
			this.serviceClass = (Class<S>) GenericsReader.getTypeArgument(
					this.getClass(), 1);
		}
		return this.serviceClass;
	}

	@SuppressWarnings("unchecked")
	private Class<E> getEntityClass() {
		if (this.instanceClass == null) {
			this.instanceClass = (Class<E>) GenericsReader.getTypeArgument(
					this.getClass(), 0);
		}
		return this.instanceClass;
	}

	@Override
	protected void onDestroy() {
		DataBaseHelper.getInstanceDBHelper().close();
		super.onDestroy();
	}
}
